﻿using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Unity;
using DelegateCommand = Prism.Commands.DelegateCommand;
using DialogParameters = Prism.Services.Dialogs.DialogParameters;

namespace SmartPlant.Modules.Base.ViewModels
{
    

    public class UserManageViewModel : ListRegionViewModel<IntoolsUser>
    {
        private ObservableCollection<IntoolsUser> _items;
        private ObservableCollection<IntoolsUser> _selectedItems;
        new public event PropertyChangedEventHandler PropertyChanged;
        public ObservableCollection<IntoolsUser> Items
        {
            get => _items;
            set
            {
                _items = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<IntoolsUser> SelectedItems
        {
            get => _selectedItems;
            set
            {
                _selectedItems = value;
                OnPropertyChanged();
            }
        }
        override protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private readonly IOAuthService _authService;
        private DelegateCommand _createUserCommand;
        private DelegateCommand _EditUserCommand;
        private DelegateCommand _deleteUserCommand;
        private DelegateCommand _setUserGroupRightCommand;
        public UserManageViewModel(
           IRegionManager regionManager,
           IUnityContainer unityContainer,
           IDialogService dialogService,
           IOAuthService oAuthService
           ) :
           base(regionManager, unityContainer, dialogService)
        {
            _authService = oAuthService;
            Items = new ObservableCollection<IntoolsUser>();
            SelectedItems = new ObservableCollection<IntoolsUser>();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        public ICommand CreateUserCommand
        {
            get
            {
                if (_createUserCommand != null) return _createUserCommand;
                _createUserCommand = new DelegateCommand(onCreateUserCommandAsync);
                return _createUserCommand;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        public ICommand EditUserCommand
        {
            get
            {
                if (_EditUserCommand != null) return _EditUserCommand;
                _EditUserCommand = new DelegateCommand(onEditUserCommandAsync);
                return _EditUserCommand;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        public ICommand DeleteUserCommand
        {
            get
            {
                if (_deleteUserCommand != null) return _deleteUserCommand;
                _deleteUserCommand = new DelegateCommand(onDeleteUserCommandAsync);
                return _deleteUserCommand;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        public ICommand SetUserGroupRightCommand
        {
            get
            {
                if (_setUserGroupRightCommand != null) return _setUserGroupRightCommand;
                _setUserGroupRightCommand = new DelegateCommand(onSetUserGroupRightCommandAsync);
                return _setUserGroupRightCommand;
            }
        }

        private void onCreateUserCommandAsync()
        {
            var para = new DialogParameters
            {
                { "userId", "" }
            };
            Dialog.ShowDialog("UserEdit", para,
                d =>
                {
                    if (d.Result == ButtonResult.OK)
                    {
                        OnInitPage(null);
                    }
                });
        }
        /// <summary>
        /// 用户分配到某个组
        /// </summary>
        private void onSetUserGroupRightCommandAsync()
        {
            if (SelectedItems.Count > 0)
            {
                
                var para = new DialogParameters
                {
                    { "user", SelectedItems.ToList()}

                };
                Dialog.ShowDialog("UserSetGroup", para,
                    d =>
                    {
                        if (d.Result == ButtonResult.OK)
                        {
                            OnInitPage(null);
                        }
                    });
            }
            else
            {
                Dialog.ShowAltert("请先选择需至少一个用户！！！");
            }


            //if (SelectObj == null)
            //{
            //    Dialog.ShowAltert("请先选择需要编辑权限的用户对象！！！");
            //    return;
            //}

            //var para = new DialogParameters
            //{
            //    { "user", SelectObj}

            //}; 
            //Dialog.ShowDialog("UserSetGroup", para,
            //    d =>
            //    {
            //        if (d.Result == ButtonResult.OK)
            //        {
            //            OnInitPage(null);
            //        }
            //    });
        }

        private void onEditUserCommandAsync()
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要编辑的用户对象！！！");
                return;
            }

            var para = new DialogParameters
            {
                { "userId", SelectObj.UserId}
            };
            Dialog.ShowDialog("UserEdit", para,
                d =>
                {
                    if (d.Result == ButtonResult.OK)
                    {
                        OnInitPage(null);
                    }
                });
        }

        private void onDeleteUserCommandAsync()
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要删除的用户对象！！！");
                return;
            }
            if (SelectObj.SystemAdminFlg == "1")
            {
                Dialog.ShowAltert("不能删除超级用户！！！");
                return;
            }

            Dialog.ShowQuestion("确认要删除当前选择的用户？", async dr =>
            {
                if (dr.Result != ButtonResult.Yes)
                    return;

                try
                {
                    var r = await _authService.DeleteUserById(SelectObj.UserId.ToString());
                    if (r.HasValue && r.Value)
                    {
                        Dialog.ShowAltert("删除用户信息成功！！！");
                        OnInitPage(null);
                    }
                }
                catch (Exception x)
                {
                    var xMessage = $"删除用户信息失败：{x.Message}！！！";
                    LoggerHelper.Current.Error(xMessage, x);
                    Dialog.ShowAltert(xMessage);
                }
            });


        }

        protected override async void OnInitPage(object obj)
        {
            try
            {
                var list = await _authService.GetAllUserList();
                DataList.Clear();
                DataList.AddRange(list);
            }
            catch (Exception x)
            {
                var xMessage = $"模板数据加载失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }
    }
}
